package net.lab1024.sa.admin.listener;


import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.CallActivity;
import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.IOParameter;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component("callActivityExecutionListener")
class CallActivityExecutionListen implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {

        CallActivity callActivity = (CallActivity) execution.getCurrentFlowElement();



        String sponsor = null; // 给子流程设置的发起人
        Map<String, List<ExtensionElement>> extensionElements = callActivity.getExtensionElements();
        for (Map.Entry<String, List<ExtensionElement>> entry : extensionElements.entrySet()) {
            // 这一层读取的就是 button 类似的标签
            String attributeName = entry.getKey();
            List<ExtensionElement> attributeValueList = entry.getValue();
            if (attributeName.equals("sponsor")) {
                for (ExtensionElement item : attributeValueList) {
                    // 处理 类似button  ExtensionElement 里面的属性
                    Map<String, List<ExtensionAttribute>> extensionElementAttributes = item.getAttributes();
                    for (Map.Entry<String, List<ExtensionAttribute>> tmpEntry : extensionElementAttributes.entrySet()) {
                        String value = tmpEntry.getValue().get(0).getValue();
                        sponsor = value; //  把子流程的发起人找到
                    }
                }
            }
        }

        List<IOParameter> ioParameterList = callActivity.getInParameters();
        for (IOParameter ioParameter : ioParameterList) {
            String source = ioParameter.getSource();
            if (source.equals("app_initiator")) {
                execution.setVariable(source, sponsor); // 把子流程
            }
        }
    }
}
